﻿/* 
 * 
 * Copyright 2013 Bendsoft. All rights reserved.
 * http://www.bendsoft.com
 * 
 * This code is distributed under the New BSD License (BSD).
 * 
 * @package     Camelot SharePoint Integration Plugins Library
 * @codeplex    http://camelottoolkit.codeplex.com
 * @license     New BSD License (BSD)
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using Camelot.SharePointIntegration.IntegrationService;
using Camelot.SharePointIntegration.IntegrationService.Entities;
using Camelot.SharePointIntegration.Client;

namespace Camelot.SharePointIntegration.Plugins
{
    internal class HTTPPostRequest
    {
        public Dictionary<string, string> Content { get; set; }

        public HTTPPostRequest()
        {
            Content = new Dictionary<string,string>();
        }

        public byte[] CreatePostData()
        {
            var builder = new StringBuilder();
            var itemCount = 0;

            foreach (var item in Content) 
            {
                itemCount += 1;
                builder.Append(item.Key);
                builder.Append("=");
                builder.Append(HttpUtility.UrlEncode(item.Value));
                if (itemCount < Content.Count)
                    builder.Append("&");
            }

            return System.Text.Encoding.UTF8.GetBytes(builder.ToString());
        }

        public static string PostData(HTTPPostRequest request, string url)
        {
            using (var webClient = new WebClient())
            {
                if (ServicePointManager.ServerCertificateValidationCallback == null)
                    ServicePointManager.ServerCertificateValidationCallback += 
                        (sender, certificate, chain, sslPolicyErrors) => true;

                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                return Encoding.UTF8.GetString(webClient.UploadData(url, "POST", request.CreatePostData()));
            }
        }
    }

    public class CamelotXmlPush : ListDataPlugin
    {
        protected override ServicePluginResult ProcessData(Task task, ListData data, List<Parameter> parameters)
        {
            string url = (from p in parameters where p.Name.ToLower() == "url" select p.Value).FirstOrDefault();
            string sharedKey = (from p in parameters where p.Name.ToLower() == "sharedkey" select p.Value).FirstOrDefault();

            if (String.IsNullOrEmpty(url))
                return new IntegrationService.ServicePluginResult() { Message = "Parameter null or empty: url" };

            var compressedXml = CamelotXml.CreateXml(data).DeflateCompress();
            var request = new HTTPPostRequest();

            request.Content.Add("xmldata", Convert.ToBase64String(compressedXml));

            if (String.IsNullOrEmpty(sharedKey))
                request.Content.Add("shared_key", sharedKey.MD5());

            try
            {
                var response = HTTPPostRequest.PostData(request, url);
            }
            catch (WebException ex)
            {
                return new IntegrationService.ServicePluginResult() { Success = false, Message = string.Format("WebException: {0}", ex.Message) };
            }

            return new IntegrationService.ServicePluginResult() { Success = true };
        }
    }
}
